package cn.minhx.dtm.demo.service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

/**
 * 数据库信息日志记录器 启动时记录数据库连接信息
 *
 * @author min
 */
@Slf4j
@Component
public class DatabaseInfoLogger implements ApplicationRunner {

	private final DataSource dataSource;

	public DatabaseInfoLogger(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public void run(ApplicationArguments args) {
		try (Connection connection = DataSourceUtils.getConnection(dataSource)) {
			DatabaseMetaData metaData = connection.getMetaData();
			System.out.println("=================================");
			System.out.println("Database URL: " + metaData.getURL());
			System.out.println("Database Driver: " + metaData.getDriverName());
			System.out.println("Database Version: " + metaData.getDatabaseProductVersion());
			System.out.println("=================================");
		} catch (SQLException e) {
			log.error("获取数据库信息失败", e);
		}
	}
}
